package com.siteseat.crudeq.broker.v1.request;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;

import com.siteseat.crudeq.broker.netty.CodecHelper;
import com.siteseat.crudeq.broker.transport.BrokerSession;
import com.siteseat.crudeq.common.raw.protocol.v1.ErrorCode;
import com.siteseat.crudeq.common.raw.protocol.v1.V1ResponseId;

/**
 *
 */
public class V1LoginHandler extends V1AbstractRequestHandler {

  /**
   * {@inheritDoc}
   */
  @Override
  public void execute( BrokerSession session, byte reqId, Channel ch, ChannelBuffer input, short version )
          throws Exception {
    login( session, ch, input, version );
  }

  /**
   * @param session
   * @param ch
   * @param input
   * @throws Exception
   */
  public void login( BrokerSession session, Channel ch, ChannelBuffer input, short version ) throws Exception {
    String userName = CodecHelper.readText( input );
    if( StringUtils.isBlank( userName ) ) {
      writeAndLogInvalidRequestError( ch, session, "Username cannot be blank" );
      return;
    }

    String password = CodecHelper.readText( input );
    if( StringUtils.isBlank( password ) ) {
      writeAndLogInvalidRequestError( ch, session, "Password cannot be blank" );
      return;
    }

    String clientId = CodecHelper.readText( input );
    if( StringUtils.isBlank( clientId ) ) {
      writeAndLogInvalidRequestError( ch, session, "Client ID cannot be blank" );
      return;
    }

    String language = CodecHelper.readText( input );
    if( StringUtils.isBlank( language ) ) {
      writeAndLogInvalidRequestError( ch, session, "Language cannot be blank" );
      return;
    }

    if( session.login( userName, password, clientId, version, new Locale( language ) ) ) {
      responseOK( ch, V1ResponseId.LOGINED );
      return;
    }

    writeAndLogError( ch, session, ErrorCode.AUTHENTICATION_FAILED, "Authentication failed: userName=" + userName
            + ", password=" + password + ", clientId=" + clientId );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean needAuthentication( BrokerSession session, Channel ch, ChannelBuffer input, byte reqId )
          throws Exception {
    return false;
  }
}
